<?php 
class Payment_Alipay_Refund extends Data_Item
{
    public function __construct ()
    {
        parent::__construct();
        $this->_commTableName = 'alipay_refund';
    }

    public function addRefundOrder($orderDetail, $refundMoneyYuan)
    {
        $row = array(
            'transactionId' => Arr::get($orderDetail, 'transactionId'),
            'orderNo'       => Arr::get($orderDetail, 'orderNo'),
            'orderId'       => Arr::get($orderDetail, 'id'),
            'refundMoney'   => $refundMoneyYuan,
            'created'       => DB::expr('unix_timestamp(now())'),
            'changed'       => DB::expr('unix_timestamp(now())'),
            'batchNo'       => '',
            'status'        => 0,
            'refundReason'  => '订单退款',
            'resultMessage' => '',
        );

        if (empty($row['transactionId']))
            return FALSE;

        $count = $this->counts(array('orderId', '=',$row['orderId']));
        if ($count > 0)
            return FALSE;

        $insert_id = $this->insert($row);
        return $insert_id;
    }

    public function setResult($arrResult)
    {
        foreach ($arrResult as $rs)
        {
	        if ($rs['codeMsg'] == 'TRADE_HAS_CLOSED')
		        continue;

            $transId = $rs['transactionId'];
            $status  = $rs['codeMsg'] == 'SUCCESS' ?  1 : 2;
	        $msg     = $rs['codeMsg'];

            if ($msg == 'SUCCESS')
            {
                $refund = new Payment_Refund;
                $orderId = $refund->getOrderIdFromTransactionId($transId);
                $refund->setRefundSuccess($orderId);
            }
        }
    }

    // 支付宝有密退款
    public function doRefund ($arrRequest)
    {
        require_once(DOCROOT."/resource/alipay_refund/alipay.config.php");
        require_once(DOCROOT."/resource/alipay_refund/lib/alipay_submit.class.php");

        // **************************请求参数**************************

        //服务器异步通知页面路径
        $notify_url = "http://www.wayatrip.com/payment/notify_refund";
        //需http://格式的完整路径，不允许加?id=123这类自定义参数
        //卖家支付宝帐户
        $seller_email = "zhaoyang.lu@wayatrip.com";
        //退款当天日期
        $refund_date = date("Y-m-d H:i:s");
        //必填，格式：年[4位]-月[2位]-日[2位] 小时[2位 24小时制]:分[2位]:秒[2位]，如：2007-10-01 13:13:13
        //批次号
        $batch_no    = date("YmdHis");
        //必填，格式：当天日期[8位]+序列号[3至24位]，如：201008010000001
        //退款笔数
        $batch_num = count($arrRequest);
        //必填，参数detail_data的值中，“#”字符出现的数量加1，最大支持1000笔（即“#”字符出现的数量999个）
        //退款详细数据
        $detail_data = "";
        //必填，具体格式请参见接口技术文档

        $arrTmps = array();
        foreach ($arrRequest as $rs)
        {
            if (!isset($rs['comment']) || empty($rs['comment']))
                $rs['comment'] = '订单退款';

            $arrTmps[] = $rs['transactionId'] .'^'. $rs['moneyYuan'] .'^'.$rs['comment'];
        }
        $detail_data = implode('#', $arrTmps);


        //构造要请求的参数数组，无需改动
        $parameter = array(
			"service"       => "refund_fastpay_by_platform_pwd",
			"partner"       => trim($alipay_config['partner']),
			"notify_url"	=> $notify_url,
			"seller_email"	=> $seller_email,
			"refund_date"	=> $refund_date,
			"batch_no"	    => $batch_no,
			"batch_num"	    => $batch_num,
			"detail_data"	=> $detail_data,
			"_input_charset"=> trim(strtolower($alipay_config['input_charset']))
        );

        //建立请求
        $alipaySubmit = new AlipaySubmit($alipay_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter,"get", "确认");

        return $html_text;
    }
}
